<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <template #header>
        <el-button
          type="primary"
          size="default"
          icon="el-icon-plus"
          @click="addDialog"
          >添加</el-button
        >
      </template>
      <!-- card body -->

      <el-table border stripe :data="trademarkList">
        <el-table-column type="index" width="80" label="序号" />
        <el-table-column label="品牌名称" prop="tmName"> </el-table-column>

        <el-table-column label="品牌LOGO">
          <template v-slot="{ row }">
            <img width="100" :src="row.logoUrl" />
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              @click="updateTm(row)"
              type="warning"
              size="small"
              icon="el-icon-edit"
              >修改</el-button
            >
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="deleteOne(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      :title="tmInfo.id ? '修改品牌' : '新增品牌'"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form
        :model="tmInfo"
        ref="ruleFormRef"
        label-width="100px"
        :inline="false"
        size="normal"
        :rules="rules"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="tmInfo.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmInfo.logoUrl" :src="tmInfo.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addOrUpdateTrademark"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqTrademarkList,
  reqAddTrademark,
  reqUpdateTrademark,
  reqDeleteTrademark
} from "@/api/product/trademark";

export default {
  name: "Trademark",
  data() {
    const validateTmName = (rule, value, callback) => {
      if (value.length > 10) {
        callback(new Error("品牌名称的长度不能大于10"));
      } else {
        callback();
      }
    };
    const validateLogoUrl = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请上传图片"));
      } else {
        callback();
      }
    };
    return {
      currentPage: 1,
      pageSize: 3,
      pageSizes: [3, 5, 10, 15],
      total: 0,
      trademarkList: [],
      dialogVisible: false,
      tmInfo: {
        logoUrl: "",
        tmName: ""
      },
      BASE_URL: "http://gmall-h5-api.atguigu.cn",

      rules: {
        tmName: [
          {
            required: true,
            validator: validateTmName,
            trigger: ["blur", "change"]
          }
        ],
        logoUrl: [
          { required: true, validator: validateLogoUrl, trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    // 初始化请求品牌列表
    async getTrademarkList() {
      let result = await reqTrademarkList(this.currentPage, this.pageSize);
      // console.log(result);
      this.trademarkList = result.data.records;
      this.total = result.data.total;
    },
    // 每页条数和当前页的改变
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.tmInfo.logoUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    addDialog() {
      this.dialogVisible = true;
      // console.log(this.$refs.ruleFormRef);

      // 清除表单校验信息！！！！
      this.$nextTick(function() {
        this.$refs.ruleFormRef.clearValidate();
      });

      // 清除表单信息
      try {
        this.tmInfo = {
          logoUrl: "",
          tmName: ""
        };
      } catch (error) {
        this.$message({
          message: "整体校验失败",
          type: "error"
        });
      }
    },
    async addOrUpdateTrademark() {
      try {
        // 表单校验
        await this.$refs.ruleFormRef.validate();

        if (this.tmInfo.id) {
          // 修改
          await reqUpdateTrademark(this.tmInfo);

          this.$message({
            message: "修改品牌成功",
            type: "success"
          });
        } else {
          // 新增
          await reqAddTrademark(this.tmInfo);
          this.$message({
            message: "新增品牌成功",
            type: "success"
          });
        }

        this.dialogVisible = false;
        this.getTrademarkList();
      } catch (error) {
        return this.$message({
          message: error,
          type: "error"
        });
      }
    },
    async updateTm(row) {
      this.tmInfo = { ...row };
      this.dialogVisible = true;

      this.$nextTick(function() {
        this.$refs.ruleFormRef.clearValidate();
      });
    },
    async deleteOne(row) {
      try {
        await reqDeleteTrademark(row.id);

        this.getTrademarkList();
      } catch (error) {
        this.$message({
          message: error.message,
          type: "error"
        });
      }
    }
  },
  mounted() {
    this.getTrademarkList();
  },
  watch: {
    currentPage: {
      immediate: true,
      handler() {
        this.getTrademarkList();
      }
    },
    pageSize: {
      immediate: true,
      handler() {
        this.getTrademarkList();
      }
    }
  }
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
